import {
  createRouter,
  createWebHashHistory,
  type RouteLocationNormalized
} from "vue-router";
import routes from "./routes";
import { useCachedViewStoreHook } from "@/store/modules/cachedView";
import NProgress from "@/utils/progress";
import setPageTitle from "@/utils/set-page-title";
import useUserStore from "@/store/modules/user";

const router = createRouter({
  history: createWebHashHistory(),
  routes
});

export interface toRouteType extends RouteLocationNormalized {
  meta: {
    title?: string;
    noCache?: boolean;
  };
}

router.beforeEach(async (to: toRouteType, from, next) => {
  // NProgress.start();

  // 查询用户信息
  console.log('ss', to);
  if (to.name === 'social') {
    next();
  } else {
    if (useUserStore().roles.length === 0 && to.name !== 'login') await useUserStore().getInfo();
    // 路由缓存
    useCachedViewStoreHook().addCachedView(to);
    // 页面 title
    setPageTitle(to.meta.title);
    next();
  }
});

router.afterEach(() => {
  NProgress.done();
});

export default router;
